package cn.itcast.web.controller.cargo;


import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.*;

import cn.itcast.domain.cargo.Invoice;
import cn.itcast.domain.cargo.InvoiceExample;
import cn.itcast.domain.cargo.Packing;
import cn.itcast.service.cargo.InvoiceService;
import cn.itcast.service.cargo.PackingService;

import cn.itcast.web.controller.BaseController;
import cn.itcast.web.utils.BeanMapUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import net.sf.jasperreports.engine.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import cn.itcast.web.utils.FileUploadUtil;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/cargo/invoice")
public class InvoiceController extends BaseController {

    @Reference
    private InvoiceService invoiceService;

    @Reference
    private ShippingOrderService shippingOrderService;



    @Reference
    private PackingService packingService;
    @Reference
    private ExportService exportService;
    @Reference
    private ContractService contractService;
    @Autowired
    private FileUploadUtil fileUploadUtil;

    @RequestMapping("/list")
    public String list(@RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "5") Integer pageSize) {

        InvoiceExample invoiceExample = new InvoiceExample();
        invoiceExample.createCriteria().andCompanyIdEqualTo(getLoginUserCompanyId());
        PageInfo<Invoice> pageInfo = invoiceService.findByPage(invoiceExample, pageNum, pageSize);
        request.setAttribute("pageInfo", pageInfo);

        return "cargo/invoice/invoice-list";

    }


    @RequestMapping("/toAdd")
    public String toAdd(String shippingOrderId) {

        System.out.println("+++++++++++++++++++++++++++++++++++"+shippingOrderId);
        Packing packing = packingService.findById(shippingOrderId);
        Double invoiceMoney= packing.getPackingMoney();
        String exportIds = packing.getExportIds();
        String[] exportIdArr = exportIds.split(",");

        String contractNo = "";
        String tradeTerms = "";


        for (int i = 0; i < exportIdArr.length; i++) {
            String exId = exportIdArr[i];
            Export export = exportService.findById(exId);

            contractNo += export.getCustomerContract() + " ";
            String contractIds = export.getContractIds();
            String[] contractIdArr = contractIds.split(",");
            for (int j = 0; j < contractIdArr.length; j++) {
               String contractId = contractIdArr[j];
                Contract contract = contractService.findById(contractId);
               invoiceMoney += contract.getTotalAmount();
                if(j==contractIdArr.length-1){
                   tradeTerms += contract.getTradeTerms();
               }else {
                    tradeTerms += contract.getTradeTerms()+",";
                }
            }
        }
        request.setAttribute("invoiceMoney",invoiceMoney);
        request.setAttribute("contractNo",contractNo);
        request.setAttribute("tradeTerms",tradeTerms);
        request.setAttribute("shippingOrderId",shippingOrderId);
        return "cargo/invoice/invoice-add";
    }

    @RequestMapping("/edit")
    public String edit(Invoice invoice, MultipartFile pickup_Photo) throws Exception {
        //补全数据
        invoice.setCompanyId(getLoginUserCompanyId());
        invoice.setCompanyName(getLoginUserCompanyName());
        invoice.setCreateBy(getLoginUser().getId());
        invoice.setCreateDept(getLoginUser().getDeptId());
        invoice.setState(0);

        if (!pickup_Photo.isEmpty()){
            String url = fileUploadUtil.upload(pickup_Photo);
            invoice.setPickupPhoto("http://"+url);
        }
        invoiceService.save(invoice);

        ShippingOrder shippingOrder = shippingOrderService.findById(invoice.getShippingOrderId());
        if(shippingOrder!=null) {
            shippingOrder.setState(1);
            shippingOrderService.update(shippingOrder);
        }
        return "redirect:/cargo/invoice/list.do";
    }


    @RequestMapping("/delete")
    @ResponseBody
    public String delete(String invoiceId){
        Invoice invoice = invoiceService.findById(invoiceId);
        if(invoice.getState()==0){
            invoiceService.delete(invoiceId);
            return "true";
        }else {
            return "false";
        }
    }

    @RequestMapping("/toInvoice")
    @ResponseBody
    public String toInvoice(String shippingOrderId){
        ShippingOrder shippingOrder = shippingOrderService.findById(shippingOrderId);
        if(shippingOrder.getState()==1){
            return "false";
        }else {
            return "true";
        }
    }


    @RequestMapping("/invoicePdf")
    @ResponseBody
    public void invoicePdf(String invoiceId) throws JRException, IOException {

        //通知浏览器以附件的形式下载
        response.setHeader("content-disposition","attachment;filename=invoice.pdf");
        //1. 得到模板的输入流
        InputStream inputStream = session.getServletContext().getResourceAsStream("/jasper/invoice.jasper");

        Invoice invoice = invoiceService.findById(invoiceId);
        ShippingOrder shippingOrder = shippingOrderService.findById(invoice.getShippingOrderId());
        Map<String, Object> map = BeanMapUtils.beanToMap(invoice);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String date = simpleDateFormat.format(invoice.getInvoiceTime());
        map.put("createTime",date);
        map.put("customName","AAA");
        map.put("lcNo",shippingOrder.getLcNo());
        map.put("constractNo",invoice.getScNo());
        map.put("orderType",shippingOrder.getOrderType());
        map.put("portOfLoading",shippingOrder.getPortOfLoading());
        map.put("protOfDischar",shippingOrder.getPortOfDischar());
        map.put("tel","15602275130");
        map.put("fax","020-75130");



        JasperPrint jasperPrint = JasperFillManager.fillReport(inputStream,map,new JREmptyDataSource());
        //3. 把pdf文件输出
        /*
            exportReportToPdfStream(JasperPrint jasperPrint, OutputStream outputStream)
                    jasperPrint： jasperprint的对象
                    outputStream: 输出的目标地址的输出流对象
         */
        JasperExportManager.exportReportToPdfStream(jasperPrint,response.getOutputStream());

    }

}
